package com.qiaofang.applet.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.*;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.constants.switchConfigConstants;
import com.qiaofang.applet.service.member.service.dto.ContactListDTO;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.domain.SignContact;
import com.qiaofang.applet.service.other.domain.SwitchConfig;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.SignContactService;
import com.qiaofang.applet.service.other.service.dto.ContactDetailsQueryDto;
import com.qiaofang.applet.service.other.service.dto.SignContactListDto;
import com.qiaofang.applet.service.other.service.dto.SignContactQueryDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.qiaofang.applet.constants.SignConstants.CONTACT_API;
import static com.qiaofang.applet.constants.SignConstants.SIGN_API;

/**
 * @author: youqing.yang
 * @create: 2020/10/13 16:39
 **/
@Slf4j
@RestController
@RequestMapping("/api/web/auth/memberSignContact")
@Api(tags = "会员：我的电子合同")
public class MemberSignContactController {

    private static RestTemplate restTemplate = new RestTemplate();

    @Autowired
    CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private SignContactService signContactService;

    @PostMapping("/getEdealsStatus")
    @ApiOperation(value = "查询电子合同开关", notes = "查询电子合同开关")
    public DataResponse<Boolean> getEdealsStatus() {
        Corporation corporation = corporationService.getCorporationByCorporationCode(QfContextHolder.getContext().getCorporationCode());
        SwitchConfig switchConfig = corporation.getSwitchConfig();
        if (switchConfig == null) {
            return DataResponse.ok(false);
        } else if (StringUtils.equals(switchConfig.getEDeals(), switchConfigConstants.OPEN.getValue())) {
            return DataResponse.ok(true);
        } else {
            return DataResponse.ok(false);
        }
    }

    @PostMapping("/getMyEdealsV1")
    @ApiOperation(value = "查询我的电子合同", notes = "查询我的电子合同")
    public DataResponse<Page<SignContactListDto>> getMySignContact(@RequestBody @Valid PageDataRequest<SignContactQueryDto> request){
        Page<SignContact> signContacts = signContactService.listSignContact(request.getParam(), PageUtil.getPageable(request));
        Page<SignContactListDto> signContactListDtos = signContactService.convertDomainToEstateListDto(signContacts);
        return DataResponse.ok(signContactListDtos);
    }

    @PostMapping("/getMyContactDetails")
    @ApiOperation(value = "电子合同详情", notes = "电子合同详情")
    public DataResponse<String> getMyContactDetails(@RequestBody @Valid DataRequest<ContactDetailsQueryDto> request) {

        DataResponse dataResponse = new DataResponse();

        try {
            Corporation corporation = corporationService.getCorporationByCorporationCode(QfContextHolder.getContext().getCorporationCode());
            if (corporation == null){
                throw new BusinessException("集团不存在");
            }
            String appId = corporation.getPullAppId();
            String appKey = corporation.getPullAppKey();
            String domain = corporation.getPullDomain();

            String companyUuid = cityCompanyService.getCompanyUuid(request.getParam().getCityCode(), QfContextHolder.getContext().getCorporationCode());
            HttpHeaders headers = getHeaders(companyUuid, appId, appKey);
            MiniProgramContactRequest requestParam = new MiniProgramContactRequest();
            requestParam.setContactUuid(request.getParam().getContactUuid());

            JSONObject result = restTemplate.postForEntity(domain + CONTACT_API, new HttpEntity<>(requestParam, headers), JSONObject.class).getBody();
            log.info("getMyEdeals http result:{}", result);
            if (StringUtils.equals("1", result.get("responseCode").toString())) {
                dataResponse.setStatus(1);
                dataResponse.setMessage("成功");
                dataResponse.setT(result.get("contactUrl"));
            }
        } catch (RestClientException e) {
            log.error("getMyEdeals error:{}", e);
            dataResponse.setStatus(2);
            dataResponse.setMessage("失败");
        }
        return dataResponse;
    }

    private HttpHeaders getHeaders(String companyUuid, String appId, String appKey) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", appId);
        headers.add("X-AUTH-KEY", appKey);
        headers.add("companyUuid", companyUuid);
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }

}
